package parser

import (
	"github.com/valyala/fasttemplate"
	"io"
	"strings"
)

const (
	templatePrefix = "${"
	templateSuffix = "}"

	translatePrefix = "["
	translateSuffix = "]"
)

func ParseTemplate(pattern string, params map[string]interface{}) string {
	t := fasttemplate.New(pattern, templatePrefix, templateSuffix)
	return t.ExecuteStringStd(params)
}

func ExecuteFuncStringWithErr(pattern string, f fasttemplate.TagFunc) (string, error) {
	t := fasttemplate.New(pattern, templatePrefix, templateSuffix)
	return t.ExecuteFuncStringWithErr(f)
}

func HasExpr(str string) bool {
	str = strings.TrimSpace(str)
	return strings.Contains(str, templatePrefix) && strings.Contains(str, templateSuffix)
}

func IsIterator(str string) bool {
	str = strings.TrimSpace(str)
	if !(strings.HasPrefix(str, templatePrefix) && strings.HasSuffix(str, templateSuffix)) {
		return false
	}
	return strings.Contains(str, "loop")
}

func IsTranslateExpr(str string) bool {
	str = strings.TrimSpace(str)
	return strings.HasPrefix(str, translatePrefix) && strings.HasSuffix(str, translateSuffix)
}

func GetExpr(str string) string {
	t := fasttemplate.New(str, templatePrefix, templateSuffix)
	return t.ExecuteFuncString(func(w io.Writer, tag string) (int, error) {
		return w.Write([]byte(strings.TrimSpace(tag)))
	})
}
